<?php
/**
 * Description of Reader
 *
 * @author chedim
 */
class oReader extends oClass implements oInterfaceReader
{
    /**
     *
     * @var oInterfaceQueue
     */
    protected $source;

    public function  __construct(oByteBuffer $source)
    {
        $this->source = $source;
    }

    public function Read($count = 1) {
        $this->CheckReadable();
        $ret = new oByteArray();
        while ($byte = $this->source->shift()) {
            $ret[] = $byte;
            if(count($ret)+1 > $count) break;
        }
        return $ret;
    }

    public function ReadTo($limiter) {
        $this->CheckReadable();
        $return = array();
        $al     = array();
        if (!is_array($limiter)) {
            $limiter = str_split($limiter);
        }
        while(true)
        {
            try {
                 $byte = $this->source->shift();
            } catch (eListEmpty $e) {
                break;
            }
            $al[] = $byte;
            for($i=0;$i<count($al);$i++) {
                if ($al[$i] != $limiter[$i]) {
                    $return = array_merge($return, $al);
                    $al = array();
                    continue;
                }
            }
            if (count($al) == count($limiter)) return $return;
        }
        return $return;
    }

    public function CanRead()
    {
        return !$this->source->is_empty();
    }

    protected function CheckReadable()
    {
        if (!$this->CanRead())
        {
            throw new eNotReadable();
        }
    }

}
?>
